package com.jsle.financial.action;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.util.WebUtils;

import com.jsle.common.artifactory.UserContext;
import com.jsle.financial.domain.User;
import com.jsle.financial.service.UserService;
import com.jsle.financial.service.UsergroupService;
import com.jsle.financial.util.AJAXUtil;
import com.jsle.financial.util.Constants;
import com.jsle.financial.util.JsonUtil;
import com.jsle.financial.util.Tools;
import com.jsle.financial.vo.Result;
import com.jsle.financial.vo.UserAndUserGroup;

/**
 * 用户登录Controller
 * @author wisdying
 * @date 2012-10-26
 */
@Controller
@RequestMapping("/login")
public class LoginController {
	private Log log = LogFactory.getLog(LoginController.class);
	private SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	@Resource
	private UserService userService;
	@Resource
	private UsergroupService usergroupService;
	/**
	 * 表单对象绑定方式传参
	 */
	@RequestMapping(value = "/addUsery.do",method=RequestMethod.GET)
	public Model addUsery(User user,Model model){
		System.out.println("##"+user.getLoginName());
		System.out.println("##"+user.getcNName());
		
		
		user.setcNName(Tools.enCodeStr(user.getcNName()));
		user.setPositionName(Tools.enCodeStr(user.getPositionName()));
		userService.addUser(user);
		User user1 = new User();
		user1.setLoginName("test1");
		Result rs = userService.queryUserByLoginName(user1);
		System.out.println(((User)rs.getResultValue()).getPositionName());
		return model;
	}
	
//	/**
//	 * 使用ServletAPI方式传参
//	 * @param request
//	 * @param response
//	 * @param model
//	 * @return
//	 */
//	@RequestMapping(value = "/addUserx")
//	public Model addUserx(HttpServletRequest request,HttpServletResponse response,Model model){
//		String loginName = WebUtils.findParameterValue(request, "loginName");
//		System.out.println("@@@"+loginName);
//		return model;
//	}
	
	@RequestMapping(value = "/addUser.do",method=RequestMethod.POST)
	public Model addUser(User user,Model model){
		System.out.println("##"+user.getLoginName());
		System.out.println("##"+user.getcNName());
		
		
		user.setcNName(Tools.enCodeStr(user.getcNName()));
		user.setPositionName(Tools.enCodeStr(user.getPositionName()));
		userService.addUser(user);
		return model;
	}
	
	@RequestMapping(value = "/forwordPage",produces = "application/json")
	@ResponseBody
	public ModelAndView forwordPage(User user){
		System.out.println("###"+user.getLoginName());
		return new ModelAndView("/ret?p=0");
	}
	/**
	 * 验证用户是否存在及分配资源
	 * 1,账户是否存在，2，身份信息确认 3，访问资源装载 
	 * @param id
	 * @param model
	 * @return
	 */
//	@RequestMapping(value = "/delUser.do",produces = "application/json")
//	@ResponseBody
//    public Model valideUserInfo(HttpServletRequest request,HttpServletResponse response,Model model){
//		String loginName = WebUtils.findParameterValue(request, "loginName");
//		String password = WebUtils.findParameterValue(request, "password");
//		//账户是否存在
//		User user = new User();
//		user.setLoginName(loginName);
//		Result rs = userService.queryUserByLoginName(user);
//		user = (User)rs.getResultValue();
//		if(user != null && user.getLoginPassword().equals(password)){
//			//确认是否为管理员
//			
//			//装配资源
//		}
//		return model;
//	}
	
	@RequestMapping(value = "/valideUserInfo.do",method=RequestMethod.POST)
	@ResponseBody
	public ModelAndView valideUserInfo(HttpServletRequest request,HttpServletResponse response){
		AJAXUtil.setCharacterEncoding(request,response);
		String loginName = WebUtils.findParameterValue(request, "loginName");
		String loginPassword = WebUtils.findParameterValue(request, "loginPassword");
		//1.登录校验
		User user = new User();
		user.setLoginName(loginName);
		Result rs = userService.queryUserByLoginName(user);
		user = (User)rs.getResultValue();
		boolean returnFlag = false;
		
		UserContext.setOnlineUser(user);
		
		if(user != null && user.getLoginPassword().equals(loginPassword)){
			returnFlag = true;
		}
		//2.向Seseion中设置相关参数，以便在页面上进行显示判断
		Result usergroupResult = usergroupService.queryUserAndUserGroupByUser(user);
		UserAndUserGroup uaus = null;
		if(usergroupResult.getResultCode()==Constants.FC_RESULT_SUCCESS_CODE){
			uaus = (UserAndUserGroup)usergroupResult.getResultValue();
		}
		//传到前台名页面用于信息显示
		request.getSession().setAttribute("workflowRole", uaus==null?Constants.GroupKey.GROUPKEY_NAN:uaus.getGroupKey());
		request.getSession().setAttribute("user", user);
		request.getSession().setAttribute("cNName", user.getcNName());
		request.getSession().setAttribute("loginTime", sdf.format(user.getCreateTime()));
		request.getSession().setAttribute("positionName", user.getPositionName());
		request.getSession().setAttribute("onliners", UserContext.getLogin().size());
		request.getSession().setAttribute("userId", user.getId());
		request.getSession().setAttribute("companeyCode", user.getCompanyCode());
		
		
		if(uaus!=null){
		}
		//3.登录成功后页面转向
		String forwardUrl = "login";
		if(returnFlag && (Constants.UserType.USER_ROLE_ISADMIN==user.getUserType())){//管理员转后台首页面
			forwardUrl = "backstage_index";//后台主页面
		}
		if(returnFlag && Constants.UserType.USER_ROLE_ISNORMAL==user.getUserType()){
			forwardUrl = "main_index";//主页面
		}
		AJAXUtil.setCharacterEncoding(response);
		return new ModelAndView(forwardUrl);
	}
	
	/**
	 * 表单对象绑定方式传参
	 */
	@RequestMapping(value = "/addUser",produces = "application/json")
	@ResponseBody
	public Model addUser2(User user,Model model){
		System.out.println("##"+user.getLoginName());
		System.out.println("##"+user.getcNName());
		StringBuffer sb = new StringBuffer();
		sb.append("{").append("\"loginName\"").append(":").append("\"zhangyq\"").append(",").append("\"cNName\"").append(":").append("\"测试\"").append("}");
		String json = sb.toString();
		System.out.println("###"+json);
		model.addAttribute("data", json);
		return model;
	}
	/**
	 * 使用ServletAPI方式传参
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "/addUserx")
	public void addUserx(HttpServletRequest request,HttpServletResponse response){
		AJAXUtil.setCharacterEncoding(request,response);
		String loginName = WebUtils.findParameterValue(request, "loginName");
		System.out.println("@@@"+loginName);
		AJAXUtil.writerJson(response,Tools.getReturnBooleanJson("true"));
	}
	
	
	@RequestMapping(value = "/getJsonStr.do",method=RequestMethod.POST)
	@ResponseBody
	public void getJsonStr(HttpServletRequest request,HttpServletResponse response){
		AJAXUtil.setCharacterEncoding(request,response);
		System.out.println("getJson()####"+Tools.getReturnBooleanJson("true"));
		User user = new User("zhangyq","123","多拉米","员工",new Date(),new Date(),1);
		try {
			System.out.println(JsonUtil.toJson(user));
			AJAXUtil.writerJson(response,"true");
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	@RequestMapping(value = "/addEntry.do",produces = "application/json")
	@ResponseBody
	public Model addEntry(User user,Model model){
		System.out.println("##"+user.getLoginName());
		System.out.println("##"+user.getcNName());
		User users = new User("zhangyq","123","测试","员工",new Date(),new Date(),1);
		try {
			model.addAttribute("data", JsonUtil.toJson(users));
		} catch (IOException e) {
			e.printStackTrace();
		}
		return model;
	}
	@RequestMapping(value = "/addEntrys",produces = "application/json")
	@ResponseBody
	public List<User> addEntrys(User user,Model model){
		List<User> ret = new ArrayList<User>();
		System.out.println("##"+user.getLoginName());
		System.out.println("##"+user.getcNName());
		User users = new User("zhangyq","123","测试","员工",new Date(),new Date(),1);
		ret.add(users);
		return ret;
	}
	
	@RequestMapping(value = "/destroy.do",method=RequestMethod.POST)
	@ResponseBody
	public ModelAndView destroy(HttpServletRequest request,HttpServletResponse response){
		String forwardUrl = "login";
		User user = (User)request.getSession().getAttribute("user");
		UserContext.removeOnlineUser(user);
		AJAXUtil.setCharacterEncoding(response);
		return new ModelAndView(forwardUrl);
	}
}
